package com.ece.core.config;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;

/**
 * 
 * This class validates the inputs provided via tha
 * com.ece.core.xmlconfigadapters. It also provides access to various parsers.
 * 
 * @author Senthu Sivasambu, http://ca.linkedin.com/in/sivasambu
 * 
 */
public class XMLConfigExtensionHandler {

	public final static String XML_CONFIG_EXT_ID = "com.ece.core.xmlconfigadapters";

	private final Map<String, IConfigAdapter> registry = new HashMap<String, IConfigAdapter>();

	private static XMLConfigExtensionHandler instance;

	private XMLConfigExtensionHandler()
	/* no explicit instantiation */
	{

	}

	public synchronized static XMLConfigExtensionHandler getInstance() {
		if (instance == null) {
			instance = new XMLConfigExtensionHandler();
		}
		return instance;
	}

	public void handleExtension() {
		Logger.getAnonymousLogger().log(Level.INFO,
				"Evaluating '" + XML_CONFIG_EXT_ID + "' extensions ...");
		IConfigurationElement[] elements = Platform.getExtensionRegistry()
				.getConfigurationElementsFor(XML_CONFIG_EXT_ID);
		for (IConfigurationElement e : elements) {
			try {
				final Object obj = e.createExecutableExtension("class");
				if (obj instanceof IConfigAdapter) {
					IConfigAdapter adapter = (IConfigAdapter) obj;
					Logger.getAnonymousLogger().log(Level.INFO,
							"Found Adapter: '" + adapter.getLog());
					registry.put(e.getContributor().getName(), adapter);
				}
			} catch (CoreException ce) {
				ce.printStackTrace();
			}
		}

	}

	public IConfigAdapter getAdapterExtension(String contributerID) {
		return registry.get(contributerID);
	}
}
